<?php
namespace control;

/*
*完工率统计类
*/

class completionRateClass extends adIndexClass
{
    private const page = 'completionRate';
    private const title = '完工率统计';
    private array $typeOption = ['生产加工', '生产返工'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => "单据日期",
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo'  => [
                        'name'  => '生产计划单号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'sourceNo'         => [
                        'name'  => '源单编号',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'type'          => [
                        'name'  => '加工类型',
                        'width' => 100,
                    ],
                    'line'          => [
                        'name'  => '生产线',
                        'width' => 200,
                    ],
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'materialName'          => [
                        'name'  => '物料名称',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 60,
                    ],
                    'salesNum'          => [
                        'name'  => '销售订单数量',
                        'width' => 120,
                    ],
                    'num'          => [
                        'name'  => '生产计划数量',
                        'width' => 120,
                    ],
                    'notIn'          => [
                        'name'  => '待入库数量',
                        'width' => 120,
                    ],
                    'rate'          => [
                        'name'  => '完成率',
                        'width' => 120,
                    ],
                    'inspection_num'          => [
                        'name'  => '待检数量',
                        'width' => 120,
                    ],
                    'qualified_num'          => [
                        'name'  => '质检合格数量',
                        'width' => 120,
                    ],
                    'unqualified_num'          => [
                        'name'  => '质检不合格数量',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                    "生产计划单号"   => text(array("name" => "orderNo")),
                    "关联源单编号"   => text(array("name" => "sourceNo")),
                ],
                [
                    "加工单类型"   => select(array('name'=>'type','option'=>$this->typeOption)),
                    '生产线'  =>  selectMultiple(["name" => "lineId", 'table' => "product_line", 'where'=>"coid = '".self::$coid."'",'sqlId' => 'id','field'=>"concat(workshop,'-',name) as name,id", 'sqlField' => 'name', 'class' => 'width200']),
                    "产品编码" => text(array("name" => "code")),
                ],
                [
                    "产品名称" => text(array("name" => "materialName")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组machiningOrder
        $like = array(
            "b.orderNo" => $this->post('orderNo'),//证件编号
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
            "a.sourceNo" => $this->post('sourceNo'),
        );
        //全等查询数组
        $equal = array(
            "b.orderType" => $this->post('type'),
            "b.lineId" => $this->post('lineId'),
            "b.coid"=>self::$coid,
            "b.state"=>'已确认'
        );
        $and = match ($this->post('state')) {
            '待入库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from machining_in_order_detail where sourceId = b.id)) = 0",
            '部分入库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from machining_in_order_detail where sourceId = b.id)) > 0 and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from machining_in_order_detail where sourceId = b.id)) < (select ifnull(sum(orderNum),0) from inventory_detail where sourceId in (select id from machining_in_order_detail where sourceId = b.id))",
            '已入库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from machining_in_order_detail where sourceId = b.id)) = (select ifnull(sum(orderNum),0) from inventory_detail where sourceId in (select id from machining_in_order_detail where sourceId = b.id))",
            default=>'',
        };
        if ($this->post('createTime')) {
            //单据日期
            $and.=self::timeComparison($this->post('createTime'),field: "b.recordDate");
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.recordDate desc,b.orderNo,a.list',
            "sort" => $this->post('list_sort') ?: "asc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array(
            "table" => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'field'=>"a.*,c.code,c.name as materialName,c.model,b.endDate,b.lineId,b.orderNo,b.type,b.recordDate",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            $salesNum = $array['sourceTable']?query($array['sourceTable'],"id = '$array[sourceId]'")['num']:0;
            //已入库数量
            $in_num = find(array('table'=>'inventory_detail','where'=>"sourceId in (select id from machining_in_order_detail where sourceId = '$array[id]')",'sum'=>"num"));
            $rate = $array['num']>0?round($in_num/$array['num']*100,1):0;
            //待检数量
            $inspection_num = find(array('table'=>'quality_order','where'=>"coid = '".self::$coid."' and type = 2 and sourceTable = 'machining_in_order' and state = '待质检' and sourceMxId in (select id from machining_in_order_detail where sourceId = '$array[id]')",'sum'=>"num"));
            $qualified_num = find(array('table'=>'quality_order','where'=>"coid = '".self::$coid."' and type = 2 and sourceTable = 'machining_in_order' and state = '已质检' and sourceMxId in (select id from machining_in_order_detail where sourceId = '$array[id]')",'sum'=>"passNum"));
            $unqualified_num = find(array('table'=>'quality_order_reason','where'=>"coid = '".self::$coid."' and orderId in (select id from quality_order where coid = '".self::$coid."' and type = 2 and sourceTable = 'machining_in_order' and state = '已质检' and sourceMxId in (select id from machining_in_order_detail where sourceId = '$array[id]'))",'sum'=>"num"));
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $product_line = query('product_line',"id = '$array[lineId]'");
                        $row[] = $product_line['workshop'].'-'.$product_line['name'];
                        break;
                    case 'salesNum':
                        $row[] = self::lostZero($salesNum,'numPrecision');
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case 'notIn':
                        $row[] = self::notLessThanZero($array['num']-$in_num);
                        break;
                    case 'rate':
                        $row[] = $rate;
                        break;
                    case 'inspection_num':
                        $row[] = $inspection_num;
                        break;
                    case 'qualified_num':
                        $row[] = $qualified_num;
                        break;
                    case 'unqualified_num':
                        $row[] = $unqualified_num;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(a.num),0) as num",
        ]);
        $inventory = find(array(
            'table'  => ' machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId join machining_in_order_detail as miod on miod.sourceId = a.id join inventory_detail as mx on mx.sourceId = miod.id ',
            'single'=>$where,
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = c.unit_one THEN mx.num*c.unit_one_num WHEN mx.unit = c.unit_two THEN mx.num*c.unit_two_num ELSE mx.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)),0) AS num"
        ));
        //待检数量
        $inspection = find(array(
            'table'  => ' machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId join machining_in_order_detail as miod on miod.sourceId = a.id join quality_order as mx on mx.sourceMxId = miod.id ',
            'single'=>$where." and mx.type = 2 and mx.sourceTable = 'machining_in_order' and mx.state = '待质检' ",
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = c.unit_one THEN mx.num*c.unit_one_num WHEN mx.unit = c.unit_two THEN mx.num*c.unit_two_num ELSE mx.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $qualified = find(array(
            'table'  => ' machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId join machining_in_order_detail as miod on miod.sourceId = a.id join quality_order as mx on mx.sourceMxId = miod.id ',
            'single'=>$where." and mx.type = 2 and mx.sourceTable = 'machining_in_order' and mx.state = '已质检' ",
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = c.unit_one THEN mx.passNum*c.unit_one_num WHEN mx.unit = c.unit_two THEN mx.passNum*c.unit_two_num ELSE mx.passNum END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $unqualified = find(array(
            'table'  => ' machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId join machining_in_order_detail as miod on miod.sourceId = a.id join quality_order as mx on mx.sourceMxId = miod.id join quality_order_reason as qor on qor.orderId = mx.id ',
            'single'=>$where." and mx.type = 2 and mx.sourceTable = 'machining_in_order' and mx.state = '已质检' ",
            'field'=>"ifnull(SUM((CASE WHEN mx.unit = c.unit_one THEN qor.num*c.unit_one_num WHEN mx.unit = c.unit_two THEN qor.num*c.unit_two_num ELSE qor.num END)/(CASE WHEN a.unit = c.unit_one THEN c.unit_one_num WHEN a.unit = c.unit_two THEN c.unit_two_num ELSE 1 END)),0) AS num"
        ));
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'notIn'        => self::formattingFigure($totalQuery['num'] - $inventory['num'], 'numPrecision'),
            'inspection_num'        => self::lostZero($inspection['num'], 'numPrecision'),
            'qualified_num'        => self::lostZero($qualified['num'], 'numPrecision'),
            'unqualified_num'        => self::lostZero($unqualified['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 不能为负数
     */
    public static function notLessThanZero($value)
    {
        if (self::isNull($value) || $value < 0){
            return 0;
        }
        return $value;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "machining_order_mx as a join machining_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
                    'field'=>"a.*,c.code,c.name as materialName,c.model,b.endDate,b.lineId,b.orderNo,b.type,b.recordDate",
                    "where" => "a.id in ('".implode("','", $checkedId)."') order by b.recordDate desc,b.orderNo,a.list",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $salesNum = $array['sourceTable']?query($array['sourceTable'],"id = '$array[sourceId]'")['num']:0;
                //已入库数量
                $in_num = find(array('table'=>'inventory_detail','where'=>"sourceId in (select id from machining_in_order_detail where sourceId = '$array[id]')",'sum'=>"num"));
                $rate = $array['num']>0?round($in_num/$array['num']*100,1):0;
                //待检数量
                $inspection_num = find(array('table'=>'quality_order','where'=>"coid = '".self::$coid."' and type = 2 and sourceTable = 'machining_in_order' and state = '待质检' and sourceMxId in (select id from machining_in_order_detail where sourceId = '$array[id]')",'sum'=>"num"));
                $qualified_num = find(array('table'=>'quality_order','where'=>"coid = '".self::$coid."' and type = 2 and sourceTable = 'machining_in_order' and state = '已质检' and sourceMxId in (select id from machining_in_order_detail where sourceId = '$array[id]')",'sum'=>"passNum"));
                $unqualified_num = find(array('table'=>'quality_order_reason','where'=>"coid = '".self::$coid."' and orderId in (select id from quality_order where coid = '".self::$coid."' and type = 2 and sourceTable = 'machining_in_order' and state = '已质检' and sourceMxId in (select id from machining_in_order_detail where sourceId = '$array[id]'))",'sum'=>"num"));
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '生产计划单号'=>$array['orderNo'],
                            '源单编号'=>$array['sourceNo'],
                            '加工类型'=>$array['type'],
                            '生产线'=>productLineClass::getName($array['lineId']),
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '销售订单数量'=>$salesNum,
                            '生产计划数量'=>$array['num'],
                            '待入库数量'=>self::notLessThanZero($array['num']-$in_num),
                            '完成率'=>$rate,
                            '待检数量'=>$inspection_num,
                            '质检合格数量'=>$qualified_num,
                            '质检不合格数量'=>$unqualified_num,
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }

            $text = $this->control['name'] . "导出了完工率统计表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "完工率统计表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'生产计划单号',
                    'aliasName'=>'生产计划单号',
                ],
                [
                    'columnName'=>'源单编号',
                    'aliasName'=>'源单编号',
                ],
                [
                    'columnName'=>'加工类型',
                    'aliasName'=>'加工类型',
                ],
                [
                    'columnName'=>'生产线',
                    'aliasName'=>'生产线',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'销售订单数量',
                    'aliasName'=>'销售订单数量',
                ],
                [
                    'columnName'=>'生产计划数量',
                    'aliasName'=>'生产计划数量',
                ],
                [
                    'columnName'=>'待入库数量',
                    'aliasName'=>'待入库数量',
                ],
                [
                    'columnName'=>'完成率',
                    'aliasName'=>'完成率',
                ],
                [
                    'columnName'=>'待检数量',
                    'aliasName'=>'待检数量',
                ],
                [
                    'columnName'=>'质检合格数量',
                    'aliasName'=>'质检合格数量',
                ],
                [
                    'columnName'=>'质检不合格数量',
                    'aliasName'=>'质检不合格数量',
                ],
            ]
        };
    }
}

